package com.alex;

import static com.anythink.core.api.ATInitMediation.getStringFromMap;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;

import com.anythink.core.api.ATBiddingListener;
import com.anythink.core.api.ATBiddingResult;
import com.anythink.core.api.MediationInitCallback;
import com.anythink.nativead.unitgroup.api.CustomNativeAd;
import com.anythink.nativead.unitgroup.api.CustomNativeAdapter;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTDrawFeedAd;
import com.bytedance.sdk.openadsdk.TTFeedAd;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class AlexGromoreNativeAdapter extends CustomNativeAdapter {

    boolean isC2SBidding = false;
    String slotId;
    AlexGromoreConfig mATConfig;

    @Override
    public void loadCustomNetworkAd(final Context context, Map<String, Object> serverExtra,
                                    Map<String, Object> localExtra) {
        if (!(context instanceof Activity)) {
            notifyATLoadFail("", "Gromore: context must be activity");
            return;
        }
        if (!initAndVerifyRequestParams(context, serverExtra, localExtra)) {
            notifyATLoadFail("", "app_id or slot_id is empty!");
            return;
        }

        AlexGromoreInitManager.getInstance()
                .initSDK(context, serverExtra, new MediationInitCallback() {
                    @Override
                    public void onSuccess() {
                        if (isC2SBidding) {
                            mATConfig.mAdCount = 1;
                        }
                        //start load native
                        AdSlot.Builder adSlotBuilder = new AdSlot.Builder().setCodeId(slotId)
                                .setImageAcceptedSize(mATConfig.mWidth, mATConfig.mHeight)
                                .setAdCount(mATConfig.mAdCount);

                        AdSlot adSlot = adSlotBuilder.build();

                        TTAdNative adNativeLoader = TTAdSdk.getAdManager()
                                .createAdNative((Activity) context);//必须传入Activity才会有加载回调
                        //draw feed
                        if (TextUtils.equals(mATConfig.mUnitType, "2")) {
                            adNativeLoader.loadDrawFeedAd(adSlot,
                                    new TTAdNative.DrawFeedAdListener() {
                                        @Override
                                        public void onError(int i, String s) {
                                            notifyATLoadFail("" + i, s);
                                        }

                                        @Override
                                        public void onDrawFeedAdLoad(List<TTDrawFeedAd> list) {
                                            if (list != null && list.size() > 0) {
                                                TTFeedAd tempAd = list.get(0);
                                                if (tempAd.getMediationManager().isExpress()) {
                                                    loadExpressFeedAd(list);
                                                } else {
                                                    loadSelfRenderFeedAd(context, list);
                                                }
                                            } else {
                                                notifyATLoadFail("", "Gromore: ExtraLoad no ad.");
                                            }
                                        }
                                    });
                        } else {
                            //normal feed
                            adNativeLoader.loadFeedAd(adSlot, new TTAdNative.FeedAdListener() {
                                @Override
                                public void onError(int i, String s) {
                                    notifyATLoadFail("" + i, s);
                                }

                                @Override
                                public void onFeedAdLoad(List<TTFeedAd> list) {
                                    if (list != null && list.size() > 0) {
                                        TTFeedAd tempAd = list.get(0);
                                        if (tempAd.getMediationManager().isExpress()) {
                                            loadExpressFeedAd(list);
                                        } else {
                                            loadSelfRenderFeedAd(context, list);
                                        }
                                    } else {
                                        notifyATLoadFail("", "Gromore: ExtraLoad no ad.");
                                    }
                                }
                            });
                        }

                    }

                    @Override
                    public void onFail(String errorMsg) {
                        notifyATLoadFail("", errorMsg);
                    }
                });

    }

    @Override
    public boolean startBiddingRequest(Context context, Map<String, Object> serverExtra,
                                       Map<String, Object> localExtra,
                                       ATBiddingListener biddingListener) {
        isC2SBidding = true;
        loadCustomNetworkAd(context, serverExtra, localExtra);
        return true;
    }

    private boolean initAndVerifyRequestParams(Context context, Map<String, Object> serverExtra,
                                               Map<String, Object> localExtra) {
        String appId = getStringFromMap(serverExtra, "app_id");
        slotId = getStringFromMap(serverExtra, "slot_id");

        if (TextUtils.isEmpty(appId) || TextUtils.isEmpty(slotId)) {
            return false;
        }
        mATConfig = new AlexGromoreConfig(context, serverExtra);
        mATConfig.parseNativeDefaultData(localExtra);
        mATConfig.mAdCount = mRequestNum;
        return true;
    }

    private void loadExpressFeedAd(List<? extends TTFeedAd> list) {
        AlexGromoreNativeExpressHandler mobrainATNativeExpressHandler = new AlexGromoreNativeExpressHandler(
                list);
        mobrainATNativeExpressHandler.startRender(
                new AlexGromoreNativeExpressHandler.RenderCallback() {
                    @Override
                    public void onRenderSuccess(List<AlexGromoreNativeExpressHandler.TTNativeExpressAdWrapper> ttNativeExpressAds) {
                        List<CustomNativeAd> resultList = new ArrayList<>();
                        List<TTFeedAd> tempList = new ArrayList<>();
                        for (AlexGromoreNativeExpressHandler.TTNativeExpressAdWrapper ttNativeExpressAdWrapper : ttNativeExpressAds) {
                            AlexGromoreExpressNativeAd ttNativeAd = new AlexGromoreExpressNativeAd(
                                    ttNativeExpressAdWrapper.ttFeedAd,
                                    ttNativeExpressAdWrapper.expressWidth,
                                    ttNativeExpressAdWrapper.expressHeight);
                            resultList.add(ttNativeAd);
                            tempList.add(ttNativeExpressAdWrapper.ttFeedAd);
                        }

                        CustomNativeAd[] customNativeAds = new CustomNativeAd[resultList.size()];
                        customNativeAds = resultList.toArray(customNativeAds);
                        notifyLoadSuccess(tempList, customNativeAds);
                    }

                    @Override
                    public void onRenderFail(String s, int i) {
                        notifyATLoadFail(String.valueOf(i), s);
                    }
                });
    }

    private void loadSelfRenderFeedAd(Context context, List<? extends TTFeedAd> list) {
        List<CustomNativeAd> resultList = new ArrayList<>();
        for (TTFeedAd ttFeedAd : list) {
            AlexGromoreNativeAd ttNativeAd = new AlexGromoreNativeAd(context, ttFeedAd,
                    mATConfig.canInterrupt, mATConfig.videoPlayBitmap, mATConfig.videoPlaySize);
            resultList.add(ttNativeAd);
        }

        CustomNativeAd[] customNativeAds = new CustomNativeAd[resultList.size()];
        customNativeAds = resultList.toArray(customNativeAds);
        notifyLoadSuccess(list, customNativeAds);
    }

    private void notifyLoadSuccess(final List<? extends TTFeedAd> nativeAdList,
                                   final CustomNativeAd... nativeAds) {

        if (nativeAdList.size() == 0 || nativeAds.length == 0) {
            notifyATLoadFail("", "Ad list is empty.");
            return;
        }

        if (isC2SBidding) {
            TTFeedAd ttFeedAd = nativeAdList.get(0);
            runOnNetworkRequestThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (mBiddingListener != null) {
                            double price = 0;
                            try {
                                price = Double.parseDouble(
                                        ttFeedAd.getMediationManager()
                                                .getBestEcpm()
                                                .getEcpm());//return cent
                                price = price / 100;//cast to yuan
                            } catch (Throwable t) {

                            }
                            if (price <= 0) {
                                price = AlexGromoreUtil.getBestPriceInCacheNew(
                                        ttFeedAd);
                            }

                            mBiddingListener.onC2SBiddingResultWithCache(
                                    ATBiddingResult.success(price,
                                            System.currentTimeMillis() + "",
                                            null, mATConfig.mCurrency),
                                    nativeAds[0]);
                        }
                    } catch (Throwable e) {

                    }
                }
            });
        } else {
            if (mLoadListener != null) {
                mLoadListener.onAdCacheLoaded(nativeAds);
            }
        }
    }


    @Override
    public void destory() {

    }

    @Override
    public String getNetworkPlacementId() {
        return slotId;
    }

    @Override
    public String getNetworkSDKVersion() {
        return AlexGromoreInitManager.getInstance().getNetworkVersion();
    }

    @Override
    public String getNetworkName() {
        return AlexGromoreInitManager.getInstance().getNetworkName();
    }
}
